<template>
  <div style="max-width: 1200px;margin: 50px auto;height: 85vh">
    <el-form :inline="true" :model="queryParams" class="demo-form-inline">
      <el-form-item label="订单状态">
        <el-select v-model="queryParams.status" placeholder="请选择订单状态" style="width: 200px">
          <el-option label="全部" :value="null"></el-option>
          <el-option label="待付款" value="1"></el-option>
          <el-option label="待发货" value="2"></el-option>
          <el-option label="待收货" value="3"></el-option>
          <el-option label="待评价" value="4"></el-option>
          <el-option label="退款/售后" value="5"></el-option>
          <el-option label="订单取消" value="6"></el-option>
          <el-option label="已退款" value="7"></el-option>
          <el-option label="已完成" value="8"></el-option>
          <el-option label="纠纷" value="9"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchOrders">查询</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="orderList.records" stripe>
      <el-table-column type="expand">
        <template #default="{row}">
          <el-table :data="row.orderProducts">
            <el-table-column label="产品名" prop="productName" />
            <el-table-column label="产品价格" prop="productPrice" />
            <el-table-column label="产品数量" prop="productQuantity" />
            <el-table-column label="优惠信息" prop="discountId" />
            <el-table-column label="最终价格" prop="currentPrice" />
          </el-table>
        </template>
      </el-table-column>
      <el-table-column prop="orderId" label="订单编号"></el-table-column>
      <el-table-column prop="status" label="订单状态">
        <template #default="{ row }">
          {{ getStatusText(row.status) }}
        </template>
      </el-table-column>
      <el-table-column prop="totalAmount" label="订单金额"></el-table-column>
      <el-table-column prop="payAmount" label="支付金额"></el-table-column>
      <el-table-column prop="productNum" label="商品数量"></el-table-column>
      <el-table-column label="创建时间">
        <template #default="scope">
          {{ formatDate(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column prop="addressInfo.recipientName" label="收货人"></el-table-column>
      <el-table-column prop="addressInfo.addressDetail" label="收货地址"></el-table-column>
      <el-table-column prop="addressInfo.recipientPhone" label="收货手机"></el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button v-if="row.status === 1" type="success" @click="toPay(row)">去付款</el-button>
          <el-button v-if="row.status === 1" type="danger" @click="showCancelReasonDialog(row)">取消订单</el-button>
          <el-button v-if="row.status === 2" type="danger">催发货</el-button>
          <el-button v-if="row.status === 3" type="success" @click="confirmReceiptAction(row.orderId)">确认收货</el-button>
          <el-button v-if="row.status === 4" type="success" @click="showReviewDialog(row)">去评价</el-button>
          <el-button v-if="row.status === 3" type="warning" @click="showRefundReasonDialog(row)">申请退货</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryParams.current"
      :page-sizes="[10, 20, 30]"
      :page-size="queryParams.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="orderList.total"
    >
    </el-pagination>

    <!-- 取消订单理由对话框 -->
    <el-dialog v-model="cancelReasonDialogVisible" title="取消订单理由">
        <el-input v-model="cancelReason" placeholder="请输入取消订单的理由"></el-input>
      <template #footer>
        <el-button @click="cancelReasonDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmCancelOrder(currentOrder)">确定</el-button>
      </template>
    </el-dialog>

    <!-- 申请退货理由对话框 -->
    <el-dialog v-model="refundReasonDialogVisible" title="申请退货理由">
        <el-input v-model="refundReason" placeholder="请输入申请退货的理由"></el-input>
      <template #footer>
        <el-button @click="refundReasonDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRefundOrder(currentOrder)">确定</el-button>
      </template>
    </el-dialog>

    <!-- 评价对话框 -->
    <el-dialog v-model="reviewDialogVisible" title="商品评价">
        <div v-for="(cur,index) in currentProduct" :key="cur">
          <el-form :model="cur.reviewForm">
            <el-form-item label="评价内容">
              <el-input v-model="cur.reviewForm.content" type="textarea" rows="4" placeholder="请输入评价内容"></el-input>
            </el-form-item>
            <el-form-item label="上传图片">
              <el-upload
                action="http://127.0.0.1:8081/upload"
                multiple
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :limit="1"
              >
                <img v-if="cur.reviewForm.url" :src="cur.reviewForm.url" class="avatar"  alt=""/>
                <el-icon v-else class="avatar-uploader-icon" @click="handleUploadChange(index)"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      <template #footer>
        <el-button @click="reviewDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitReview()">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { getOrdersByStatusForUser, cancelOrder as cancelOrderApi, confirmReceipt as confirmReceiptApi, refundOrder as refundOrderApi, addProductReview } from '@/common/net/api';
import { ElMessage, ElMessageBox, type UploadProps } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import moment from 'moment'
import { payGO } from '@/common/net/toPay.ts'
// 查询参数
const queryParams = ref({
  status: null,
  current: 1,
  size: 10
});

// 订单列表
const orderList = ref({
  records: [],
  total: 0
});

// 取消订单理由对话框显示状态
const cancelReasonDialogVisible = ref(false);
// 申请退货理由对话框显示状态
const refundReasonDialogVisible = ref(false);
// 评价对话框显示状态
const reviewDialogVisible = ref(false);

// 当前操作的订单
let currentOrder = ref<any>({
});
// 取消订单理由
const cancelReason = ref('');
// 申请退货理由
const refundReason = ref('');
// 评价表单
const reviewForm = ref({
  content: '',
  url:''
});
let currentProduct=ref([])
let point = ref(0)
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  console.log(response);
  console.log(uploadFile);
  currentProduct.value[point.value].reviewForm.url= response.data;
  console.log(currentProduct.value[point.value].reviewForm.url);
}

const toPay = (order: any) => {
  console.log(order.orderId);
  payGO(order)
};
// 获取订单列表
const fetchOrders = async () => {
  try {
    const { data } = await getOrdersByStatusForUser(queryParams.value.status, queryParams.value.current, queryParams.value.size);
    orderList.value = data.data;
  } catch (error) {
    ElMessage.error('查询订单失败');
  }
};

// 处理每页数量变化
const handleSizeChange = (newSize: number) => {
  queryParams.value.size = newSize;
  fetchOrders();
};

// 处理当前页码变化
const handleCurrentChange = (newPage: number) => {
  queryParams.value.current = newPage;
  fetchOrders();
};

// 显示取消订单理由对话框
const showCancelReasonDialog = (order: any) => {
  currentOrder.value = order;
  cancelReason.value = '';
  cancelReasonDialogVisible.value = true;
};
const formatDate = (dateString: any) => {
  return moment(dateString).format('YYYY/MM/DD HH:mm:ss');
};
// 确认取消订单
const confirmCancelOrder = async (order: any) => {
  if (!cancelReason.value) {
    ElMessage.warning('请输入取消订单的理由');
    return;
  }
  try {
    await cancelOrderApi(order, cancelReason.value);
    ElMessage.success('订单取消成功');
    cancelReasonDialogVisible.value = false;
    fetchOrders();
  } catch (error) {
    ElMessage.error('订单取消失败');
  }
};

// 确认收货
const confirmReceiptAction = async (orderId: number) => {
  ElMessageBox.confirm('确定要确认收货吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await confirmReceiptApi(orderId);
      ElMessage.success('确认收货成功');
      fetchOrders();
    } catch (error) {
      ElMessage.error('确认收货失败');
    }
  }).catch(() => {
    // 用户取消操作
  });
};

// 显示申请退货理由对话框
const showRefundReasonDialog = (order: any) => {
  currentOrder.value = order;
  refundReason.value = '';
  refundReasonDialogVisible.value = true;
};

// 确认申请退货
const confirmRefundOrder = async (order: any) => {
  if (!refundReason.value) {
    ElMessage.warning('请输入申请退货的理由');
    return;
  }
  try {
    await refundOrderApi(order, refundReason.value);
    ElMessage.success('退货申请成功');
    refundReasonDialogVisible.value = false;
    await fetchOrders();
  } catch (error) {
    ElMessage.error('退货申请失败');
  }
};

// 显示评价对话框
const showReviewDialog = (order: any) => {
  currentOrder.value = order;
  currentProduct.value = order.orderProducts.map((product) => ({
    ...product,
    reviewForm: ref({
      content: '',
      url: ''
    })
  }));
  console.log(currentProduct.value)
  reviewDialogVisible.value = true;
};

// 提交评价
const submitReview = async () => {
  console.log(currentProduct.value[0].reviewForm.content);
  for (let product of currentProduct.value) {
      const review = {
        productId: product.productId,
        comment: product.reviewForm.content,
        url: product.reviewForm.url,
        orderId:currentOrder.value.orderId
      };
      console.log(review)
      await addProductReview(review)
      ElMessage.success('评价提交成功');
      reviewDialogVisible.value = false;
  }
  await fetchOrders();
};
// 处理文件上传变化
const handleUploadChange = (index: number) => {
  console.log(index);
  point.value = index;
};

// 根据状态码获取状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case 1:
      return '待付款';
    case 2:
      return '待发货';
    case 3:
      return '待收货';
    case 4:
      return '待评价';
    case 5:
      return '退款/售后';
    case 6:
      return '订单取消';
    case 7:
      return '已退回';
    case 8:
      return '已完成';
    case 9:
      return '纠纷';
    default:
      return '未知状态';
  }
};

onMounted(() => {
  fetchOrders();
});
</script>

<style scoped>
/* 可以添加一些自定义样式 */
</style>
